#include "stdafx.h"
#include "Texture.h"
#include "Utils.h"
#include "Marco.h"


Texture::Texture(void) : m_IdTexture(0),
m_iCount(0)
{
}

GLuint Texture::Load2DTexture(char* TextureName)
{
 	return Load2DTextures(&TextureName, 1)[0];
}

GLuint Texture::Load2DTextureAnpha(char* TextureName)
{
	return Load2DTextures(&TextureName, 1)[0];
}

GLuint* Texture::Load2DTextures(char** strTextureName, int iCount)
{
	m_TextureTarget = GL_TEXTURE_2D;
	//Set textures count
	m_iCount = iCount;

	//Init list textures id
	if (!m_IdTexture)
		Delete_Array(m_IdTexture);
	m_IdTexture = new GLuint[m_iCount];

	//Generate Texture Buffer
	glGenBuffers(m_iCount, m_IdTexture);
	
	//Binding texture data
	for (int i = 0; i < m_iCount; i++)
	{
		//Texture info
		int iWidth, iHeight, iBPP;
		char* imageData = NULL;
		GLenum eTextureFormat;

		//Load texture data from TGA file
		imageData = LoadTGA(strTextureName[i], &iWidth, &iHeight, &iBPP);
		switch (iBPP)
		{
		case 24:
			eTextureFormat = GL_RGB;
			break;
		case 32:
			eTextureFormat = GL_RGBA;
			break;
		default:
			Delete_Array(m_IdTexture);
			Delete_Array(imageData);
			return NULL;
		}

		glActiveTexture(GL_TEXTURE0+i);
		glBindTexture(m_TextureTarget, m_IdTexture[i]);
		glTexImage2D(GL_TEXTURE_2D, 0, eTextureFormat, iWidth, iHeight, 0, eTextureFormat, GL_UNSIGNED_BYTE, imageData);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(m_TextureTarget, 0);
		Delete_Array(imageData);
	}

	return m_IdTexture;
}

void Texture::Bind(GLenum TextureUnit)
{
	glActiveTexture(TextureUnit);
	glBindTexture(m_TextureTarget, m_IdTexture[0]);
}

void Texture::UnBind(GLenum TextureUnit)
{
	glActiveTexture(TextureUnit);
	glBindTexture(m_TextureTarget, 0);
}

GLuint Texture::LoadTextureCube(char** aTextureName)
{
	//m_TextureTarget = GL_TEXTURE_CUBE_MAP;
	return -1;
}

Texture::~Texture(void)
{
	Delete_Array(m_IdTexture);
}
